package com.smart.community.user.config;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MinIO配置类
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 * @version 1.0.0
 */
@Slf4j
@Configuration
public class MinioConfig {

    @Value("${minio.endpoint:http://localhost:9000}")
    private String endpoint;

    @Value("${minio.access-key:admin}")
    private String accessKey;

    @Value("${minio.secret-key:admin123}")
    private String secretKey;

    @Value("${minio.bucket-name:smart-community}")
    private String bucketName;

    @Value("${minio.secure:false}")
    private Boolean secure;

    @Value("${minio.connect-timeout:10000}")
    private Integer connectTimeout;

    @Value("${minio.read-timeout:30000}")
    private Integer readTimeout;

    @Value("${minio.write-timeout:30000}")
    private Integer writeTimeout;

    /**
     * 创建MinIO客户端
     * 
     * @return MinIO客户端
     */
    @Bean
    public MinioClient minioClient() {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            // 检查存储桶是否存在，不存在则创建
            boolean bucketExists = minioClient.bucketExists(
                    io.minio.BucketExistsArgs.builder()
                            .bucket(bucketName)
                            .build()
            );

            if (!bucketExists) {
                minioClient.makeBucket(
                        io.minio.MakeBucketArgs.builder()
                                .bucket(bucketName)
                                .build()
                );
                log.info("创建MinIO存储桶成功: {}", bucketName);
            } else {
                log.info("MinIO存储桶已存在: {}", bucketName);
            }

            log.info("MinIO客户端初始化成功，端点: {}, 存储桶: {}", endpoint, bucketName);
            return minioClient;
        } catch (Exception e) {
            log.error("MinIO客户端初始化失败: {}", e.getMessage(), e);
            log.warn("MinIO客户端初始化失败，将返回null，文件上传功能将不可用");
            return null;
        }
    }
} 